// https://leetcode.cn/problems/permutations-ii/description/

// 算法思路总结：
// 1. 回溯算法生成包含重复元素数组的所有不重复排列
// 2. 先排序数组，使相同元素相邻便于去重
// 3. 剪枝条件：当前元素未被访问，且不是重复元素或前一个相同元素已被使用
// 4. 避免在同一层级选择相同的元素产生重复排列
// 5. 时间复杂度：O(n×n!)，空间复杂度：O(n)

#include <iostream>
using namespace std;

#include <cstring>
#include <vector>
#include <algorithm>

class Solution 
{
public:
    vector<vector<int>> ret;
    vector<int> path;
    bool vis[11];
    vector<vector<int>> permuteUnique(vector<int>& nums) 
    {
        ret.clear();
        memset(vis, 0, sizeof(vis));

        sort(nums.begin(), nums.end());

        dfs(nums);

        return ret;
    }

    void dfs(vector<int>& nums)
    {
        if (path.size() == nums.size())
        {
            ret.push_back(path);
            return ;
        }

        for (int i = 0 ; i < nums.size() ; i++)
        {
            if (vis[i] == false && (i == 0 || nums[i] != nums[i - 1] || vis[i - 1] == true))
            {
                path.push_back(nums[i]);
                vis[i] = true;

                dfs(nums);

                path.pop_back();
                vis[i] = false;
            }
        }
    }
};

void printResult(const vector<vector<int>>& result) 
{
    cout << "[";
    for (int i = 0; i < result.size(); ++i) 
    {
        cout << "[";
        for (int j = 0; j < result[i].size(); ++j) 
        {
            cout << result[i][j];
            if (j < result[i].size() - 1) cout << ",";
        }
        cout << "]";
        if (i < result.size() - 1) cout << ",";
    }
    cout << "]" << endl;
}

int main()
{
    vector<int> nums1 = {1,1,2};
    vector<int> nums2 = {1,2,3};

    Solution sol;

    auto vv1 = sol.permuteUnique(nums1);
    auto vv2 = sol.permuteUnique(nums2);

    printResult(vv1);
    printResult(vv2);

    return 0;
}